#!/usr/bin/env python3
"""
调试菜单API脚本
用于验证登录和菜单API的正确性
"""

import requests
import json
import sys

def test_login_and_menu():
    """测试登录和获取菜单"""
    base_url = "http://127.0.0.1:5000"
    
    print("🔍 测试登录接口...")
    
    # 登录
    login_data = {
        "username": "admin",
        "password": "123456"
    }
    
    login_response = requests.post(f"{base_url}/admin/v1/auth/login", json=login_data)
    print(f"登录响应状态码: {login_response.status_code}")
    print(f"登录响应内容: {login_response.text}")
    
    if login_response.status_code != 200:
        print("❌ 登录失败")
        return
    
    login_result = login_response.json()
    if login_result.get('code') != 200:
        print(f"❌ 登录失败: {login_result.get('message')}")
        return
    
    token = login_result['data']['token']
    print(f"✅ 登录成功，Token: {token}")
    
    print("\n🔍 测试菜单接口...")
    
    # 获取菜单
    headers = {
        "Authorization": f"Bearer {token}",
        "Content-Type": "application/json"
    }
    
    menu_response = requests.get(f"{base_url}/admin/v1/menus?tree=true", headers=headers)
    print(f"菜单响应状态码: {menu_response.status_code}")
    print(f"菜单响应内容: {menu_response.text}")
    
    if menu_response.status_code != 200:
        print("❌ 获取菜单失败")
        return
    
    menu_result = menu_response.json()
    if menu_result.get('code') != 200:
        print(f"❌ 获取菜单失败: {menu_result.get('message')}")
        return
    
    print("✅ 菜单获取成功")
    print("\n📋 菜单数据结构:")
    print(json.dumps(menu_result['data'], indent=2, ensure_ascii=False))
    
    # 分析第一个菜单项
    if menu_result['data']:
        first_menu = menu_result['data'][0]
        print(f"\n🎯 第一个菜单项分析:")
        print(f"  名称: {first_menu.get('name')}")
        print(f"  路径: {first_menu.get('path')}")
        print(f"  可见: {first_menu.get('visible')}")
        print(f"  有子菜单: {len(first_menu.get('children', [])) > 0}")
        
        if first_menu.get('children'):
            first_child = first_menu['children'][0]
            print(f"\n  第一个子菜单:")
            print(f"    名称: {first_child.get('name')}")
            print(f"    路径: {first_child.get('path')}")
            print(f"    可见: {first_child.get('visible')}")

if __name__ == "__main__":
    try:
        test_login_and_menu()
    except Exception as e:
        print(f"❌ 测试出错: {e}")
        import traceback
        traceback.print_exc() 